<template>
	<view class="data-container">
		<!-- 渐变背景 -->
		<view class="gradient-bg"></view>
		
		<!-- 自定义导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-content">
				<view class="navbar-left" @click="goBack">
					<text class="back-icon">‹</text>
				</view>
				<text class="navbar-title">数据管理</text>
			</view>
		</view>
		
		<!-- 数据统计卡片 -->
		<view class="stats-section">
			<view class="stats-card">
				<view class="stats-header">
					<view class="header-icon">
						<text class="icon-text">📊</text>
					</view>
					<view class="header-info">
						<text class="stats-title">数据统计</text>
						<text class="stats-subtitle">最后更新：{{ lastUpdateTime }}</text>
					</view>
				</view>
				<view class="stats-grid">
					<view class="stat-item">
						<view class="stat-number">{{ memoCount }}</view>
						<view class="stat-label">备忘录总数</view>
					</view>
					<view class="stat-item">
						<view class="stat-number">{{ todayCount }}</view>
						<view class="stat-label">今日新增</view>
					</view>
					<view class="stat-item">
						<view class="stat-number">{{ importantCount }}</view>
						<view class="stat-label">重要备忘</view>
					</view>
					<view class="stat-item">
						<view class="stat-number">{{ categoryCount }}</view>
						<view class="stat-label">分类数量</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 数据管理功能 -->
		<view class="management-section">
			<view class="section-card">
				<!-- 导出数据 -->
				<view class="data-item" @click="exportData">
					<view class="item-icon export">
						<text class="icon-text">📤</text>
					</view>
					<view class="item-content">
						<text class="item-title">导出数据</text>
						<text class="item-desc">将数据导出为JSON文件</text>
					</view>
					<text class="item-arrow">›</text>
				</view>
				
				<!-- 导入数据 -->
				<view class="data-item" @click="importData">
					<view class="item-icon import">
						<text class="icon-text">📥</text>
					</view>
					<view class="item-content">
						<text class="item-title">导入数据</text>
						<text class="item-desc">从JSON文件导入数据</text>
					</view>
					<text class="item-arrow">›</text>
				</view>
			</view>
		</view>
		
		<!-- 导出格式选择弹窗 -->
		<view class="export-modal" v-if="showExportModal" @click="hideExportModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<view class="header-icon">
						<text class="icon-text">📤</text>
					</view>
					<text class="modal-title">选择导出格式</text>
					<text class="modal-subtitle">请选择您需要的导出格式</text>
				</view>
				<view class="format-list">
					<view 
						class="format-item" 
						v-for="(format, index) in exportFormats" 
						:key="index"
						@click="selectExportFormat(format)"
					>
						<view class="format-icon">
							<text class="format-emoji">{{ format.icon }}</text>
						</view>
						<view class="format-info">
							<text class="format-name">{{ format.name }}</text>
							<text class="format-desc">{{ format.desc }}</text>
						</view>
					</view>
				</view>
				<view class="modal-actions">
					<view class="action-btn cancel-btn" @click="hideExportModal">
						<text class="btn-text">取消</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 导入确认弹窗 -->
		<view class="import-modal" v-if="showImportModal" @click="hideImportModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<view class="header-icon">
						<text class="icon-text">📥</text>
					</view>
					<text class="modal-title">导入数据</text>
					<text class="modal-subtitle">选择导入方式</text>
				</view>
				<view class="import-options">
					<view class="option-item" @click="selectFile">
						<view class="option-icon">
							<text class="icon-text">📁</text>
						</view>
						<view class="option-info">
							<text class="option-name">选择文件</text>
							<text class="option-desc">从设备中选择JSON文件</text>
						</view>
					</view>
					<view class="option-item" @click="pasteJson">
						<view class="option-icon">
							<text class="icon-text">📋</text>
						</view>
						<view class="option-info">
							<text class="option-name">粘贴JSON</text>
							<text class="option-desc">直接粘贴JSON数据</text>
						</view>
					</view>
				</view>
				<view class="modal-actions">
					<view class="action-btn cancel-btn" @click="hideImportModal">
						<text class="btn-text">取消</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- JSON输入弹窗 -->
		<view class="json-modal" v-if="showJsonModal" @click="hideJsonModal">
			<view class="modal-content json-content" @click.stop>
				<view class="modal-header">
					<view class="header-icon">
						<text class="icon-text">📋</text>
					</view>
					<text class="modal-title">粘贴JSON数据</text>
					<text class="modal-subtitle">请粘贴要导入的JSON数据</text>
				</view>
				<view class="json-input-container">
					<textarea 
						v-model="jsonInput" 
						placeholder="请粘贴JSON数据..."
						class="json-textarea"
						maxlength="50000"
					></textarea>
					<text class="char-count">{{ jsonInput.length }}/50000</text>
				</view>
				<view class="modal-actions">
					<view class="action-btn cancel-btn" @click="hideJsonModal">
						<text class="btn-text">取消</text>
					</view>
					<view class="action-btn confirm-btn" @click="confirmImportJson">
						<text class="btn-text">导入</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import storage from '@/utils/storage.js'

export default {
	data() {
		return {
			statusBarHeight: 0,
			memoCount: 0,
			todayCount: 0,
			importantCount: 0,
			categoryCount: 0,
			lastUpdateTime: '',
			showExportModal: false,
			showImportModal: false,
			showJsonModal: false,
			jsonInput: '',
			exportFormats: [
				{
					name: 'JSON格式',
					desc: '完整数据备份，包含所有信息',
					icon: '📄',
					type: 'json'
				},
				{
					name: 'TXT文本',
					desc: '纯文本格式，易于阅读',
					icon: '📝',
					type: 'txt'
				},
				{
					name: 'Markdown',
					desc: 'Markdown格式，支持富文本',
					icon: '📑',
					type: 'md'
				},
				{
					name: 'CSV表格',
					desc: '表格格式，便于数据分析',
					icon: '📊',
					type: 'csv'
				}
			]
		}
	},
	
	onLoad() {
		this.getStatusBarHeight()
		this.loadStats()
		this.updateLastTime()
	},
	
	onShow() {
		this.loadStats()
	},
	
	methods: {
		// 获取适配的状态栏高度
		getStatusBarHeight() {
			const systemInfo = uni.getSystemInfoSync();
			let statusBarHeight = systemInfo.statusBarHeight || 0;
			
			// #ifdef MP-WEIXIN
			if (statusBarHeight === 0) {
				statusBarHeight = 25;
			}
			statusBarHeight = Math.max(statusBarHeight, 22);
			// #endif
			
			// #ifdef MP-ALIPAY
			if (statusBarHeight === 0) {
				statusBarHeight = 20;
			}
			// #endif
			
			// #ifdef H5
			statusBarHeight = 0;
			// #endif
			
			this.statusBarHeight = statusBarHeight;
		},
		
		goBack() {
			uni.navigateBack()
		},
		
		// 加载统计数据
		loadStats() {
			const currentUser = storage.getCurrentUser()
			if (!currentUser) return
			
			const allMemos = uni.getStorageSync('memo_data') || []
			const userMemos = allMemos.filter(memo => memo.userId === currentUser.id)
			
			this.memoCount = userMemos.length
			this.importantCount = userMemos.filter(memo => memo.important).length
			
			// 计算今日新增
			const today = new Date().toDateString()
			this.todayCount = userMemos.filter(memo => {
				const memoDate = new Date(memo.createTime).toDateString()
				return memoDate === today
			}).length
			
			// 计算分类数量
			const categories = new Set(userMemos.map(memo => memo.category || 'general'))
			this.categoryCount = categories.size
		},
		
		// 更新最后更新时间
		updateLastTime() {
			this.lastUpdateTime = new Date().toLocaleString()
		},
		
		// 导出数据
		exportData() {
			this.showExportModal = true
		},
		
		hideExportModal() {
			this.showExportModal = false
		},
		
		// 选择导出格式
		selectExportFormat(format) {
			this.hideExportModal()
			
			const result = storage.exportUserData()
			if (!result.success) {
				uni.showToast({
					title: result.message,
					icon: 'none'
				})
				return
			}
			
			let exportContent = ''
			const fileName = `小何备忘录_${new Date().toISOString().split('T')[0]}`
			
			switch(format.type) {
				case 'json':
					exportContent = JSON.stringify(result.data, null, 2)
					this.saveToFile(exportContent, `${fileName}.json`)
					break
				case 'txt':
					exportContent = this.convertToTxt(result.data)
					this.saveToFile(exportContent, `${fileName}.txt`)
					break
				case 'md':
					exportContent = this.convertToMarkdown(result.data)
					this.saveToFile(exportContent, `${fileName}.md`)
					break
				case 'csv':
					exportContent = this.convertToCsv(result.data)
					this.saveToFile(exportContent, `${fileName}.csv`)
					break
			}
		},
		
		// 转换为TXT格式
		convertToTxt(data) {
			let content = `小何备忘录数据导出\n导出时间：${data.exportTime}\n\n`
			content += `用户信息：\n用户名：${data.userInfo.username}\n昵称：${data.userInfo.nickname}\n\n`
			content += `备忘录列表：\n${'-'.repeat(50)}\n`
			
			data.memos.forEach((memo, index) => {
				content += `${index + 1}. ${memo.title}\n`
				content += `内容：${memo.content}\n`
				content += `分类：${memo.category || 'general'}\n`
				content += `重要：${memo.important ? '是' : '否'}\n`
				content += `创建时间：${memo.createTime}\n`
				content += `${'-'.repeat(30)}\n`
			})
			
			return content
		},
		
		// 转换为Markdown格式
		convertToMarkdown(data) {
			let content = `# 小何备忘录数据导出\n\n`
			content += `**导出时间：** ${data.exportTime}\n\n`
			content += `## 用户信息\n\n`
			content += `- **用户名：** ${data.userInfo.username}\n`
			content += `- **昵称：** ${data.userInfo.nickname}\n\n`
			content += `## 备忘录列表\n\n`
			
			data.memos.forEach((memo, index) => {
				content += `### ${index + 1}. ${memo.title}\n\n`
				content += `${memo.content}\n\n`
				content += `- **分类：** ${memo.category || 'general'}\n`
				content += `- **重要：** ${memo.important ? '是' : '否'}\n`
				content += `- **创建时间：** ${memo.createTime}\n\n`
				content += `---\n\n`
			})
			
			return content
		},
		
		// 转换为CSV格式
		convertToCsv(data) {
			let content = '标题,内容,分类,重要,创建时间,更新时间\n'
			
			data.memos.forEach(memo => {
				const title = `"${memo.title.replace(/"/g, '""')}"`
				const content = `"${memo.content.replace(/"/g, '""')}"`
				const category = memo.category || 'general'
				const important = memo.important ? '是' : '否'
				
				content += `${title},${content},${category},${important},${memo.createTime},${memo.updateTime}\n`
			})
			
			return content
		},
		
		// 保存文件
		saveToFile(content, fileName) {
			// 在小程序中，将内容复制到剪贴板
			uni.setClipboardData({
				data: content,
				success: () => {
					uni.showModal({
						title: '导出成功',
						content: `数据已复制到剪贴板，文件名：${fileName}`,
						showCancel: false
					})
				},
				fail: () => {
					uni.showToast({
						title: '导出失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 导入数据
		importData() {
			this.showImportModal = true
		},
		
		hideImportModal() {
			this.showImportModal = false
		},
		
		// 选择文件（在小程序中使用粘贴方式）
		selectFile() {
			this.hideImportModal()
			this.showJsonModal = true
		},
		
		// 粘贴JSON
		pasteJson() {
			this.hideImportModal()
			this.showJsonModal = true
		},
		
		hideJsonModal() {
			this.showJsonModal = false
			this.jsonInput = ''
		},
		
		// 确认导入JSON
		confirmImportJson() {
			if (!this.jsonInput.trim()) {
				uni.showToast({
					title: '请输入JSON数据',
					icon: 'none'
				})
				return
			}
			
			try {
				const importData = JSON.parse(this.jsonInput)
				this.processImportData(importData)
			} catch (error) {
				uni.showToast({
					title: 'JSON格式错误',
					icon: 'none'
				})
			}
		},
		
		// 处理导入数据
		processImportData(importData) {
			// 验证数据格式
			if (!importData.memos || !Array.isArray(importData.memos)) {
				uni.showToast({
					title: '数据格式错误',
					icon: 'none'
				})
				return
			}
			
			const currentUser = storage.getCurrentUser()
			if (!currentUser) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			uni.showModal({
				title: '确认导入',
				content: `将导入${importData.memos.length}条备忘录，是否继续？`,
				success: (res) => {
					if (res.confirm) {
						this.doImport(importData, currentUser)
					}
				}
			})
		},
		
		// 执行导入
		doImport(importData, currentUser) {
			try {
				const allMemos = uni.getStorageSync('memo_data') || []
				let importCount = 0
				
				importData.memos.forEach(memo => {
					// 为每个备忘录分配新的ID和用户ID
					const newMemo = {
						...memo,
						id: Date.now() + Math.random(),
						userId: currentUser.id,
						createTime: new Date().toISOString(),
						updateTime: new Date().toISOString()
					}
					
					allMemos.push(newMemo)
					importCount++
				})
				
				uni.setStorageSync('memo_data', allMemos)
				
				this.hideJsonModal()
				this.loadStats()
				
				uni.showToast({
					title: `成功导入${importCount}条备忘录`,
					icon: 'success'
				})
			} catch (error) {
				uni.showToast({
					title: '导入失败',
					icon: 'none'
				})
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.data-container {
	min-height: 100vh;
	position: relative;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
}

.gradient-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100vh;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
	z-index: -1;
}

.custom-navbar {
	position: relative;
	z-index: 10;
	padding-top: var(--status-bar-height);
	background: rgba(255, 255, 255, 0.1);
}

.navbar-content {
	display: flex;
	align-items: center;
	height: 88rpx;
	padding: 0 30rpx;
}

.navbar-left {
	width: 80rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: rgba(255, 255, 255, 0.2);
	transition: all 0.3s ease;
}

.navbar-left:active {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(0.95);
}

.back-icon {
	font-size: 36rpx;
	color: #ffffff;
	font-weight: bold;
}

.navbar-title {
	flex: 1;
	text-align: center;
	font-size: 36rpx;
	font-weight: 600;
	color: #ffffff;
	text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.stats-section {
	position: relative;
	z-index: 1;
	padding: 30rpx;
}

.stats-card {
	background: rgba(255, 255, 255, 1);
	border-radius: 30rpx;
	padding: 40rpx;
	box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.1);
}

.stats-header {
	display: flex;
	align-items: center;
	margin-bottom: 30rpx;
}

.header-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 15rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.icon-text {
	font-size: 28rpx;
}

.header-info {
	flex: 1;
}

.stats-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.stats-subtitle {
	font-size: 24rpx;
	color: #666;
}

.stats-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 30rpx;
}

.stat-item {
	text-align: center;
	padding: 20rpx;
	border-radius: 20rpx;
	background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
}

.stat-number {
	font-size: 48rpx;
	font-weight: 700;
	color: #667eea;
	margin-bottom: 8rpx;
	display: block;
}

.stat-label {
	font-size: 24rpx;
	color: #666;
}

.management-section {
	position: relative;
	z-index: 1;
	padding: 0 30rpx 40rpx;
}

.section-card {
	background: rgba(255, 255, 255, 1);
	border-radius: 30rpx;
	padding: 40rpx;
	box-shadow: 0 16rpx 48rpx rgba(0, 0, 0, 0.1);
}

.data-item {
	display: flex;
	align-items: center;
	padding: 30rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	transition: all 0.3s ease;
}

.data-item:last-child {
	border-bottom: none;
}

.data-item:active {
	background: rgba(102, 126, 234, 0.05);
	border-radius: 16rpx;
	margin: 0 -20rpx;
	padding: 30rpx 20rpx;
}

.item-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 30rpx;
}

.item-icon.export {
	background: linear-gradient(135deg, #51cf66 0%, #40c057 100%);
}

.item-icon.import {
	background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.item-content {
	flex: 1;
}

.item-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.item-desc {
	font-size: 26rpx;
	color: #666;
}

.item-arrow {
	font-size: 32rpx;
	color: #999;
	margin-left: 20rpx;
}

/* 弹窗样式 */
.export-modal, .import-modal, .json-modal {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
	padding: 40rpx;
	box-sizing: border-box;
}

.modal-content {
	background: #ffffff;
	border-radius: 30rpx;
	padding: 40rpx;
	width: 100%;
	max-width: 600rpx;
	max-height: 80vh;
	overflow-y: auto;
	animation: modalSlideIn 0.3s ease-out;
}

.json-content {
	max-width: 700rpx;
}

@keyframes modalSlideIn {
	from {
		opacity: 0;
		transform: translateY(50rpx) scale(0.95);
	}
	to {
		opacity: 1;
		transform: translateY(0) scale(1);
	}
}

.modal-header {
	display: flex;
	flex-direction: column;
	align-items: center;
	margin-bottom: 40rpx;
	text-align: center;
}

.modal-header .header-icon {
	width: 100rpx;
	height: 100rpx;
	border-radius: 25rpx;
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 20rpx;
}

.modal-title {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.modal-subtitle {
	font-size: 26rpx;
	color: #666;
}

.format-list {
	margin-bottom: 40rpx;
}

.format-item {
	display: flex;
	align-items: center;
	padding: 30rpx 20rpx;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	background: #f8f9fa;
	transition: all 0.3s ease;
}

.format-item:active {
	background: #e9ecef;
	transform: scale(0.98);
}

.format-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 15rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
}

.format-emoji {
	font-size: 28rpx;
}

.format-info {
	flex: 1;
}

.format-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.format-desc {
	font-size: 26rpx;
	color: #666;
}

.import-options {
	margin-bottom: 40rpx;
}

.option-item {
	display: flex;
	align-items: center;
	padding: 30rpx 20rpx;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	background: #f8f9fa;
	transition: all 0.3s ease;
}

.option-item:active {
	background: #e9ecef;
	transform: scale(0.98);
}

.option-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 15rpx;
	background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 24rpx;
}

.option-info {
	flex: 1;
}

.option-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 8rpx;
}

.option-desc {
	font-size: 26rpx;
	color: #666;
}

.json-input-container {
	margin-bottom: 30rpx;
}

.json-textarea {
	width: 100%;
	height: 300rpx;
	padding: 20rpx;
	border: 2rpx solid #e9ecef;
	border-radius: 16rpx;
	font-size: 26rpx;
	color: #333;
	background: #f8f9fa;
	box-sizing: border-box;
	resize: none;
}

.json-textarea:focus {
	border-color: #a6c0fe;
	background: #ffffff;
}

.char-count {
	display: block;
	text-align: right;
	font-size: 24rpx;
	color: #999;
	margin-top: 12rpx;
}

.modal-actions {
	display: flex;
	justify-content: center;
	gap: 20rpx;
}

.action-btn {
	flex: 1;
	height: 80rpx;
	border-radius: 20rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	font-weight: 600;
	transition: all 0.3s ease;
}

.cancel-btn {
	background: #f8f9fa;
	border: 2rpx solid #e9ecef;
}

.cancel-btn .btn-text {
	color: #666;
}

.confirm-btn {
	background: linear-gradient(135deg, #a6c0fe 0%, #f68084 100%);
}

.confirm-btn .btn-text {
	color: #ffffff;
}

.action-btn:active {
	transform: scale(0.98);
}
</style> 